package com.binvshe.binvshe.common.http;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2017/2/6
 */

public abstract class BaseParserFragment<BeanType extends Object> extends SwipeListFragment
        implements ReflexInterface<BeanType> {

    protected final static int PAGE_SIZE = 10;
    protected int lastListSize = 0;
    public int mlastid = 0;

    public MyResponseParser<BeanType> parser = new MyResponseParser<BeanType>(getReflexClass()) {

        @Override
        public boolean hasMore() {
            if (lastListSize >= PAGE_SIZE) {
                return true;
            } else {
                return false;
            }
        }
    };

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        startLoading();
    }

    protected ListDataRequestListener mRequestListener = new ListDataRequestListener(this, parser) {
        @Override
        public void onSuccess(Object listData) {
            super.onSuccess(listData);
            if (getData().size() > 0) {
                mlastid = getLastID((BeanType) getData().get(getData().size() - 1));
            }
            List<BeanType> list = (List<BeanType>) listData;
            if (list != null) {
                lastListSize = list.size();
            }
        }
    };

    public abstract int getLastID(BeanType data);

    @Override
    public abstract RecyclerViewBaseAdapter createAdapter();

    @Override
    public abstract void onStartLoading();

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        mlastid = 0;
        getData().clear();
        startLoading();
    }

    @Override
    public Class<BeanType> getReflexClass() {
        Class<BeanType> entityClass = (Class<BeanType>) ((ParameterizedType)
                this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return entityClass;
    }
}
